package com.example.server.manage.gptdialogue.server.impl;

import com.example.server.manage.gptdialogue.properties.GptProperties;
import com.example.server.manage.gptdialogue.server.ChatGptService;
import com.example.server.util.validated.ValidUtil;
import com.plexpt.chatgpt.ChatGPT;
import com.plexpt.chatgpt.entity.chat.ChatCompletion;
import com.plexpt.chatgpt.entity.chat.ChatCompletionResponse;
import com.plexpt.chatgpt.entity.chat.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ChatGptServiceImpl implements ChatGptService {

    @Autowired
    private GptProperties gptProperties;

    Proxy proxy = Proxy.NO_PROXY;

    @Override
    public Message chat(String content, String model, Integer maxTokens, Double temperature) {
        ValidUtil.isTrue(StringUtils.isBlank(content.trim()), "发送聊天内容不能为空");
        // 参数处理
        String url = gptProperties.getUrl();
        String key = gptProperties.getKeys().get(0);
        Integer timeout = gptProperties.getTimeout();
        model = StringUtils.isNotBlank(model) ? model : gptProperties.getDefaultModel();
        maxTokens = maxTokens != null ? maxTokens : gptProperties.getDefaultMaxTokens();
        temperature = temperature != null ? temperature : gptProperties.getDefaultTemperature();

        // chatGPT 构建
        ChatGPT chatGpt = ChatGPT.builder()
                .proxy(proxy)
                .apiKey(key)
                .timeout(timeout)
                .apiHost(url)
                .build()
                .init();

        // 参数构建
        List<Message> messages = new ArrayList<>();
        String[] contents = content.split("\\|\\|");
        for (String c : contents) {
            messages.add(Message.of(c));
        }

        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model(model)
                .messages(messages)
                .maxTokens(maxTokens)
                .temperature(temperature)
                .build();

        // 发起请求
        ChatCompletionResponse response = chatGpt.chatCompletion(chatCompletion);
        Message res = response.getChoices().get(0).getMessage();
        log.info("响应内容: " + res);

        // 如需持久化 把数据写到数据库
        return res;
    }
}
